import React, { Component } from 'react'

export default class App extends Component {
  userNameRef = React.createRef()
  passwordRef = React.createRef()
  avatarRef = React.createRef()
  previewRef = React.createRef()
  render() {
    return (
      <div>
        <div>
          姓名：<input type="text" ref={ this.userNameRef }/>
        </div>
        <div>
          密码：<input type="text" ref={ this.passwordRef }/>
        </div>
        <div>
          头像<input type="file" ref={ this.avatarRef } onChange = { this.getFile }/>
          <img ref = { this.previewRef } src="" alt=""/>
        </div>
        <button onClick = { this.getData }>获取数据</button>
      </div>
    )
  }
  getFile = () => {
    const file = this.avatarRef.current.files[0]
    const reader = new FileReader()
    reader.readAsDataURL(file)
    const that = this
    reader.onload = function () { // 注意this指向
      that.previewRef.current.src = this.result
    }
  }
  getData = () => {
    console.log(this.userNameRef.current)
    console.log({
      userName: this.userNameRef.current.value,
      password: this.passwordRef.current.value,
      url: this.previewRef.current.src
    })
  }
}
